/**
 * 获取随机字符串
 * @param length 随机字符串长度
 * @returns
 */
export const randomStr = (length: number) => {
  const str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let result = '';
  for (let i = 0; i < length; i++) result += str[Math.floor(Math.random() * str.length)];
  return result;
};

/**
 * 获取唯一串列号
 * @param prefix 前缀
 * @returns
 */
export const uniNumber = (prefix = '') => {
  const now = new Date();
  const year = now.getFullYear().toString().substring(2);
  const month = (now.getMonth() + 1).toString().padStart(2, '0');
  const day = now.getDate().toString().padStart(2, '0');
  const hours = now.getHours().toString().padStart(2, '0');
  const minutes = now.getMinutes().toString().padStart(2, '0');
  const seconds = now.getSeconds().toString().padStart(2, '0');
  const random = Math.floor(Math.random() * 100000)
    .toString()
    .padStart(5, '0');
  return `${prefix}${year}${month}${day}${hours}${minutes}${seconds}${random}`;
};

/**
 * 获取url的参数
 * @param url
 * @param paramName
 * @returns
 */
export const getUrlParams = (url: string, paramName: string) => {
  // 从 URL 中提取查询参数部分
  let queryString = url.split('?')[1];

  // 如果没有查询参数，返回空对象
  if (!queryString) {
    return {};
  }

  // 处理带有 hash 地址的情况
  const hashIndex = queryString.indexOf('#');
  if (hashIndex !== -1) {
    queryString = queryString.substring(0, hashIndex);
  }

  // 将查询参数字符串解析为键值对
  const queryParams: any = {};
  queryString.split('&').forEach((param) => {
    const [key, value] = param.split('=');
    // 如果值已经存在，则将其转换为数组存储
    if (queryParams[key]) {
      if (Array.isArray(queryParams[key])) {
        queryParams[key].push(decodeURIComponent(value));
      } else {
        queryParams[key] = [queryParams[key], decodeURIComponent(value)];
      }
    } else {
      queryParams[key] = decodeURIComponent(value);
    }
  });

  // 如果没有指定参数名称，则返回包含所有查询参数的对象
  if (!paramName) {
    return queryParams;
  }

  // 如果指定了参数名称
  if (queryParams[paramName]) {
    return queryParams[paramName];
  } else {
    // 参数不存在，返回空字符串
    return '';
  }
};

/**
 * 简化时间
 * @param time 时间
 * @returns
 */
export const simplifyTime = (time: string) => {
  return time.substring(0, 16);
};
